import { getDate } from '@/utils/index'
import { selectTodosByDate, save, insertTodo, updateTodoStatus, removeItem } from '@/api/system/todo'
import { Message } from 'element-ui'

const state = {
    // 当前页面上的
    inputValue: '',
    // 当前点击的日期
    targetTime: '',
    // 查询出来的集合
    todoList: [],
}

const mutations = {
    SET_CLICKTIME: (state, arg) => {
        state.targetTime = arg
    },
    SET_INPUTVALUE: (state, arg) => {
        state.inputValue = arg
    },
    SET_TODOLIST: (state, obj) => {
        state.todoList = obj
    },
    SET_DONE_TODO: (state, param) => {
        state.todoList[param.index].done = param.target
    },
    REMOVE_ITEM: (state, index) => {
        state.todoList.splice(index, 1)
    },
    ADDITEM: (state, item) => {
        state.todoList.unshift(item)
    }
}

const actions = {
    // 设置点击时间
    targetTime({ commit }, arg) {
        commit("SET_CLICKTIME", arg)
    },

    // 获取列表
    getList({ commit }, date) {
        return new Promise((resolve, reject) => {
            selectTodosByDate(date).then((res) => {
                commit('SET_TODOLIST', res.data)
                resolve(res)
            }).catch((err) => {
                reject(err)
            });
        })
    },

    // 更新
    update_value({ commit }, arg) {
        commit('SET_INPUTVALUE', arg)
    },

    // 添加列表项
    addItem({ commit, dispatch, rootState }) {
        if (state.inputValue === '') {
            Message({ showClose: true, message: '不能为空', type: "error" });
            return
        }
        // 构造列表项
        const item = {
            tId: new Date().getTime(),
            content: state.inputValue,
            userId: rootState.user.userId,
            done: 0, // 默认未完成
            createTime: getDate(),
            targetTime: state.targetTime
        };
        // 将inputValue置为空
        commit('SET_INPUTVALUE', '')
        new Promise((resolve, reject) => {
            insertTodo(item).then((res) => {
                // commit('ADDITEM', item)
                dispatch('getList', item.targetTime)
                resolve(res)
            }).catch((err) => {
                console.log(err)
                reject(err)
            });
        })
    },

    // 保存现有列表项
    save({ commit }) {
        if (state.newList.length == 0) return
        return new Promise((resovle, reject) => {
            save(state.newList).then((res) => {
                /// 页面销毁或者是切换了日期本来就会重新对todoList赋值，所以就不同置为空
                // commit('SET_TODOLIST', [])
                commit('SET_INPUTVALUE', '')
                commit('SET_NEWLIST', [])
                resovle(res)
            }).catch((err) => {
                reject(err)
            });
        })
    },

    // 更新选中框状态
    changeStatus({ commit }, obj) {
        // 菜了，想不到好的方案。出此下策
        const index = state.todoList.findIndex(item => item.tId === obj.tId)
        if (index != -1) {
            const param1 = {
                index: index,
                target: obj.done === '1' ? '0' : '1'
            }
            commit('SET_DONE_TODO', param1)
        }
        return new Promise((resolve, reject) => {
            updateTodoStatus(obj).then((res) => {
                resolve(res)
            }).catch((err) => {
                reject(err)
            });
        })
    },
    // 删除item项
    removeItem({ commit }, arg) {
        const index = state.todoList.findIndex(item => item.tId === arg)
        return new Promise((resolve, reject) => {
            removeItem(arg).then((res) => {
                commit('REMOVE_ITEM', index)
                resolve(res)
            }).catch((err) => {
                reject(err)
            });
        })
    }
}

const getters = {
    // 筛选已完成
    selectDone: state => {
        return state.todoList.filter(todo => todo.done === '1')
    },

    // 筛选未完成
    selectUnDone: state => {
        return state.todoList.filter(todo => todo.done === '0')
    },

    // 筛选剩余
    selectSurplus: state => {
        var count = 0;
        state.todoList.forEach(todo => {
            if (todo.done === '0') count++
        })
        return count
    },

    // 是否全部完成
    isAllDone: state => {
        if (state.todoList.length === 0) return false
        return state.todoList.every(todo => todo.done === '1')
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}